'''
    1. 读取cookie
    2. 读取redis
    3. 初始化了3个容器
        一个列表用于存放选中的id
        一个列表用于存放未选中的id
        一个字典用于保存cookie中的转换为hash的数据
    4. 对cookie数据进行遍历
        进行判断
    5. 更新redis
    6. cookie删除
'''
import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    carts_cookie = request.COOKIES.get('carts')
    # cookie购物车为空
    if not carts_cookie:
        return response
    # 不为空
    else:
        carts = pickle.loads(base64.b64decode(carts_cookie))
        redis_conn = get_redis_connection('carts')

        sku_id_counts = redis_conn.hgetall('carts:%s' % user.id)
        new_sku_id_counts = {}
        for sku_id, count in sku_id_counts.items():
            new_sku_id_counts[int(sku_id)] = int(count)

        selected_ids = []
        unselected_ids = []
        new_redis_carts = {}
        # 对cookie数据进行遍历 {sku_id:{count:xxx,selected:xxxx},...}
        for sku_id, selected_counts in carts.items():
            new_redis_carts[sku_id] = selected_counts['count']
            if selected_counts['selected']:
                selected_ids.append(sku_id)
            else:
                unselected_ids.append(sku_id)
        # 更新redis
        redis_conn.hmset('carts:%s' % user.id, new_redis_carts)
        if selected_ids:
            redis_conn.sadd('selected:%s' % user.id, selected_ids)
        if unselected_ids:
            redis_conn.sadd('selected:%s' % user.id, unselected_ids)
        response.delete_cookie('carts')
        return response
